﻿//  --------------------------------
//  Copyright (c) AW Systems, Inc. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.codeplex.com/SLAM/license
//  ---------------------------------

using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

namespace AWS.SLAM.Configuration
{
    public class XmlConnectionStringSection : ConnectionStringSection
    {
        private XDocument _configXml;

        /// <summary>
        /// Gets the default connection string stored in the configuration.
        /// </summary>
        /// <returns></returns>
        public override string Default
        {
            get
            {
                string connectionString = "";
                if (SlamItemContext.ListItem != null)
                {
                    IConfigurationManager configManager = ComponentService.GetInstance<IConfigurationManager>();

                    if (configManager.DataMapping is XmlSqlDataMapping)
                    {
                        connectionString = ((XmlSqlDataMapping)configManager.DataMapping).GetConnectionString();
                    }
                }

                if (String.IsNullOrEmpty(connectionString))
                {
                    connectionString = _configXml.Root.Element("ConnectionStrings").Attribute("Default").Value;
                }
                return GetConnectionString(connectionString);
            }
        }

        public XmlConnectionStringSection(XDocument configurationXml)
        {
            _configXml = configurationXml;
        }

        /// <summary>
        /// Gets a connection string stored in the configuration.
        /// </summary>
        /// <returns></returns>
        public override string GetConnectionString(string name)
        {
            string connectionString = (from field in _configXml.Root.Element("ConnectionStrings").Elements("add")
                                       where field.Attribute("Name").Value == name
                                       select field.Attribute("ConnectionString").Value).First();

            return connectionString;
        }
    }
}
